import { type PaginationProps } from "@pureadmin/table";
import { ref, computed, Transition, reactive, onMounted, nextTick } from "vue";
import {
  FunDataGetPortfolioDetailsData,
  SecuritiesClientGetClientBaseData,
  FunDataGetPortfolioDataByClientBaseId,
  SecuritiesPortfolioPurchasedPortfolio,
  SecuritiesPortfolioGetPurchasedPortfolioData,
} from "@/api/stu/Cecurity";
import { useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import { Column, RingProgress } from '@antv/g2plot';
import qs from "qs";
export function useTradeExecution() {
  const route = useRoute();
  const loading = ref<boolean>(false)
  const dataList = ref();
  const clientList = ref();
  const clientName = ref<any>();
  const Visible = ref(false);
  const VisibleDesgin = ref(false);
  const tableDesgin = ref([]);// 投资组合详情
  const clientform = ref<any>({
    clientBaseRiskType: "",//风险等级
    protfolioDatas: [],//配置方案
    configDatas: [],//资产组合
    createTime: ""
  })
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    pageSizes: [5, 10, 15],
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      minWidth: 100
    }, {
      label: "资产配置方案名称",
      prop: "projectName"
    }, {
      label: "投资组合名称",
      prop: "portfolioldName"
    }, {
      label: "客群名称",
      prop: "clientBaseName",
    }, {
      label: "模拟年化收益率(%)",
      prop: "annualYield"
    }, {
      label: "模拟年化波动率(%)",
      prop: "annualizedVolatility"
    }, {
      label: "购买日期",
      prop: "purchaseTime"
    }, {
      label: "状态",
      prop: "status"
    }
  ];
  // 匹配投资组合
  async function OpenVisible() {
    if (!clientName.value) {
      ElMessage.warning('请选择客户群')
      return
    }
    const data = {
      "planId": route.query.planId,
      "taskId": route.query.taskId,
      clientBaseId: clientName.value.clientBaseId
    };

    const res = await FunDataGetPortfolioDataByClientBaseId(qs.stringify(data));
    if (res.success) {
      const { clientBaseRiskType, protfolioDatas, configDatas } = res.data;
      Visible.value = true;
      clientform.value.clientBaseRiskType = clientBaseRiskType;
      clientform.value.protfolioDatas = protfolioDatas;
      clientform.value.configDatas = configDatas;
      setTimeout(() => {
        render(configDatas)
      }, 0)
    } else {
      ElMessage.error(res.msg)
    }
  }
  // 投资组合金额限制
  function HandScope(row) {
    if (row < 1000) {
      row = 1000
    }
    if (row > 100000000) {
      row = 100000000
    }
  }

  // 购买投资组合
  async function stubim_form() {
    const obj = Object.assign([], clientform.value.protfolioDatas);
    const filteredData = obj.filter(item => item.price !== null);
    if (clientform.value.createTime == "") {
      ElMessage.warning('请选择购买日期')
      return
    }
    if (!filteredData.length || filteredData[0].price === null || filteredData[0].price === '') {
      ElMessage.warning('请输入购买金额')
      return
    }

    if (filteredData[0].price < 1000) {
      ElMessage.warning('购买金额不能小于1000')
      return
    }
    if (filteredData[0].price > 100000000) {
      ElMessage.warning('购买金额不能小于100000000')
      return
    }

    const data = {
      "planId": route.query.planId,
      "taskId": route.query.taskId,
      amountPurchase: filteredData[0].price,
      portfolioId: filteredData[0].portfolioId,
      clientBaseId: clientName.value.clientBaseId,
      createTime: clientform.value.createTime,
    }
    const res = await SecuritiesPortfolioPurchasedPortfolio(data);
    if (res.success) {
      ElMessage.success(res.msg);
      closefrom()
      GetDataList()
    } else {
      ElMessage.error(res.msg)
    }
  }

  // 查看投资组合详情
  async function ViewVisibleDesgin(row) {
    const res = await FunDataGetPortfolioDetailsData({ fundJson: row.fundJson });
    if (res.success) {
      VisibleDesgin.value = true;
      tableDesgin.value = res.data
    } else {
      ElMessage.error(res.msg);
      tableDesgin.value = []
    }

  }

  // 调用饼图
  function render(datas) {
    datas.forEach((item, index) => {
      const data = [
        { type: "现金管理类", nums: Number(item.cashManagement), color: "#f7c122", max: 100 },
        { type: "固定收益类", nums: Number(item.fixedIncome), color: "#6395fa", max: 100 },
        { type: "权益收益类", nums: Number(item.incomeFromEquity), color: "#62daab", max: 100 },
        { type: "另类及其他", nums: Number(item.rests), color: "#657798", max: 100 },
      ];
      nextTick(() => {
        const columnPlot = new Column(`content${index}`, {
          data,
          xField: 'type',
          yField: 'nums',
          color: ({ type }) => {
            if (type === '现金管理类') {
              return '#f7c122';
            } else if (type === '固定收益类') {
              return '#6395fa';
            } else if (type === '权益收益类') {
              return '#62daab';
            } else {
              return '#657798';
            }
          },
          xAxis: {
            label: {
              autoHide: true,
              autoRotate: false,
            }
          },
          yAxis: {
            max: 100,
          },
          meta: {
            value: {
              max: 100,
              min: 0,
            },
          },
        });
        /////////////////////////
        // 预期收益率
        const ringProgres = new RingProgress(`yqsyl${index}`, {
          height: 100,
          width: 100,
          autoFit: false,
          percent: Number(item.expectedYield) / 100,
          color: ['#E6A23C', '#faecd8'],
          innerRadius: 0.85,
          radius: 0.98,
          statistic: {
            title: {
              style: { color: '#363636', fontSize: '12px', lineHeight: '14px', fontWeight: '600' },
              formatter: () => '预期收益率',
            },
          },
        });

        // 预期波动率
        const ringProgress = new RingProgress(`yqbdl${index}`, {
          height: 100,
          width: 100,
          autoFit: false,
          percent: Number(item.expectedVolatility) / 100,
          color: ['#F56C6C', '#fcd3d3'],
          innerRadius: 0.85,
          radius: 0.98,
          statistic: {
            title: {
              style: { color: '#363636', fontSize: '12px', lineHeight: '14px', fontWeight: '600' },
              formatter: () => '预期波动率',
            },
          },
        });

        setTimeout(() => {
          columnPlot.render();
          ringProgres.render();
          ringProgress.render();
        }, 300)

      })
    })
  }

  // 关闭弹窗
  function closefrom() {
    Visible.value = false
    clientform.value.createTime = ""
  }

  // 获取交易列表
  async function GetDataList() {
    const data = {
      taskId: route.query.taskId,
      planId: route.query.planId,
      pageIndex: pagination.currentPage,
      pageCount: pagination.pageSize,
      clientName: clientName.value
    };
    const res = await SecuritiesPortfolioGetPurchasedPortfolioData(data);
    if (res.success) {
      dataList.value = res?.data?.items;
      pagination.total = res?.data?.totalCount
    } else {
      ElMessage.error(res.msg);
    }
  }

  // 获取客户群列表
  async function GetClientNameList() {
    const data = {
      "planId": route.query.planId,
      "taskId": route.query.taskId
    }
    const res = await SecuritiesClientGetClientBaseData(data);
    if (res.success) {
      clientList.value = res?.data?.data
    } else {
      ElMessage.error(res.msg);
    }
  }

  function handleSizeChange() { GetDataList() }
  function handsleCurrentChange() { GetDataList() }

  onMounted(() => {
    GetDataList()
    GetClientNameList()
  })

  return {
    Visible,
    loading,
    dataList,
    columns,
    clientName,
    clientList,
    pagination,
    clientform,
    tableDesgin,
    VisibleDesgin,
    ViewVisibleDesgin,
    handleSizeChange,
    handsleCurrentChange,
    stubim_form,
    OpenVisible,
    HandScope,
    closefrom,
  }
}
